package graduate.wangyaqi.Account;

import graduate.wangyaqi.Service.MailService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(path="/User")
public class AccountController {
    @Autowired
    private UserService userService;

    @PostMapping(path="/insert")
    public boolean InsertUser(@RequestBody User user){
        User item = userService.findByEmail(user.getEmail());
        if(item!=null){
            return false;
        }
        userService.save(user);
        return true;
    }

    @GetMapping(path="/deleteAll")
    public void DeleteAll(){
        userService.deleteAll();
    }

    @GetMapping(path="/delete")
    public void Delete(long id){
        userService.delete(id);
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        return userService.getAll();
    }

    // 验证是否存在用户邮箱2
    @GetMapping(path="/ConfirmHaveEmail")
    public Boolean ConfirmHaveEmail(String email){
        User user= userService.findByEmail(email);
        return user!=null;
    }

    // 账户密码获取用户
    @GetMapping(path="/GetUser")
    public User GetUser(String email, String password) {
        return userService.findUserByEmailAndPassword(email, password);
    }

    @GetMapping(path = "/AlterPassword")
    public void AlterPassword(String email,String password){
        User user = userService.findByEmail(email);
        userService.save(user);
    }

    @GetMapping(path = "/ValidateCode")
    public boolean ValidateCode(String email,String randNum){
        User user = userService.findByEmail(email);
        String str = user.getRandNum();
        boolean res = str.equals(randNum);
        return res;
    }

    @GetMapping(path="/SendEmail")
    public boolean SendEmail(String email){
        String num = MailService.SendEmail(email);
        User user = userService.findByEmail(email);
        user.setRandNum(num);
        userService.save(user);

        return true;
    }
}
